package cc.rengu.igas.route.common.dao.impl;

import cc.rengu.igas.route.common.dao.MultiRatioWeightCfgMapper;
import cc.rengu.igas.route.common.entity.MultiRatioWeightCfg;
import cc.rengu.oltp.service.common.constant.AppConfigConstant;
import cc.rengu.oltp.service.common.constant.AppParamConstant;
import cc.rengu.oltp.utility.util.DbsUtil;
import cc.rengu.oltp.utility.util.XmlConfigUtil;
import cc.rengu.oltp.utility.util.XmlTreeUtil;
import cc.rengu.utility.base.StringUtil;
import cc.rengu.utility.cache.UnifiedCache;
import cc.rengu.utility.log.RgLog;
import cc.rengu.utility.log.RgLogger;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 多路比例动态权重配置表操作类
 *
 * @author xlz
 * @version 1.0
 * @date 2020-03-13
 */
public class MultiRatioWeightCfgMapperImpl implements MultiRatioWeightCfgMapper {
    private RgLogger rglog = RgLog.getLogger(this.getClass().getName());
    private String dbPoolName = XmlConfigUtil.getXmlConfigCacheKeyValue(AppConfigConstant.DATABASE_CONF_NODE, AppConfigConstant.ROUTE_POOL_NAME);

    public MultiRatioWeightCfgMapperImpl() throws Exception {
        XmlTreeUtil xmlTreeUtil = new XmlTreeUtil();
        String corporation = xmlTreeUtil.getXmlTreeStringValue(AppParamConstant.CORPORATION);
        if (null != corporation && !corporation.isEmpty()) {
            String dbPoolCashNode = corporation.trim() + AppParamConstant.DATABASE_CONF_NODE;
            dbPoolName = XmlConfigUtil.getXmlConfigCacheKeyValue(dbPoolCashNode, AppConfigConstant.ROUTE_POOL_NAME);
        }
    }

    @Override
    public List<MultiRatioWeightCfg> getMultiRatioWeightCfg(String instId, int ruleId) throws Exception {
        DbsUtil dbsUtil = new DbsUtil(dbPoolName);
        String sqlStr = (String) UnifiedCache.get(AppParamConstant.SQL_MAPPER_CACHE, "getMultiRateRouteCfg");
        if (StringUtil.isNullorEmpty(sqlStr)) {
            throw new Exception("获取数据操作SQL失败");
        }

        MultiRatioWeightCfg multiRatioWeightCfg = new MultiRatioWeightCfg();
        multiRatioWeightCfg.setRuleId(ruleId);
        multiRatioWeightCfg.setInstId(instId);

        List<Object> objectList = dbsUtil.dbsFetchLimitListData(sqlStr, multiRatioWeightCfg, MultiRatioWeightCfg.class);
        if (null == objectList || objectList.isEmpty()) {
            rglog.error("根据规则id<{}>查询所有多路比例路由信息失败!", ruleId);
            return null;
        }
        return objectList.stream().map(item -> (MultiRatioWeightCfg) item).collect(Collectors.toList());
    }
}
